import { IObject, udp } from '@cscec/udp-mobile-ui';
// 获取音频Blob并转换为File
export const audioToFile = async (audioURL: string, fileName: string = 'audio.wav'): Promise<File> => {
  try {
    // 获取音频数据
    const response = await fetch(audioURL);
    const blob = await response.blob();
    
    // 将Blob转换为File
    const file = new File([blob], fileName, {
      type: blob.type || 'audio/wav',
      lastModified: Date.now(),
    });
    
    return file;
  } catch (error) {
    console.error('转换音频为文件失败:', error);
    throw error;
  }
};

// 发送文件到后端
export const uploadAudioFile = async (file: File) => {
  const formData = new FormData();
  formData.append('audio', file);
  formData.append('timestamp', new Date().toISOString());
  
  try {
    const response = await fetch('/api/admin/getWord', {
      method: 'POST',
      body: formData,
      // 注意：使用FormData时不要设置Content-Type，浏览器会自动设置
    });
    
    if (!response.ok) {
      throw new Error(`上传失败: ${response.statusText}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('上传音频文件失败:', error);
    throw error;
  }
};

// 组合使用
export const processAndUploadAudio = async (audioURL: string, fileName: string= 'audio.wav') => {
  try {
    const audioFile = await audioToFile(audioURL, fileName);
    console.log(audioFile)
    const result = await uploadAudioFile(audioFile);
    return result;
  } catch (error) {
    console.error('处理音频失败:', error);
    throw error;
  }
};